// components/address/index.js
import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
import { initLocationPersmiss, judgeAuth } from '../../utils/util';
const $api = require('../../request/api').API;
const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {},
  observers: {},
  /**
   * 组件的初始数据
   */
  data: {
    beeperId: '', //传过来的呼叫器
    info: {}, //父组件传过来的一些东西其它信息
    addressInfo: {},
    addressType: '',
    // 1: 呼叫器地址及联系人
    // 2: 呼叫器地址和下单联系人
    // 3: 符合条件的就近收货地址
    // 4: 呼叫器地址和门牌号
    // 5: 用户新地址
    existAddress: false, //是否存在地址
    addAddress: '', //如果为1表示需要新增地址，如果为2表示已经新增过了
    harvestAddressId: '', //收获地址id
    address: '',
    villageName: '',
    houseNumber: '',
    linkName: '',
    phone: '',
    inputHouseNumber: '', //输入的门牌号
    inputPhone: '', // 输入的电话
    inputPerson: '', // 输入的姓名
    showAddressPicker: false,
    addressList: []
  },
  pageLifetimes: {
    async show() {
      const { exceed, harvestAddressId, linkName, phone, houseNumber, villageName, address } = app.globalData;
      if (exceed || app.globalData.delete) {
        // 如果修改的地址是现在选中的地址超出了范围就需要把选中地址清空
        if (harvestAddressId == this.data.harvestAddressId) {
          this.setData({
            harvestAddressId: '',
            linkName: '',
            phone: '',
            address: '',
            houseNumber: '',
            villageName: ''
          });
        }
        this.showAddressPopup();
      } else if (harvestAddressId) {
        // 地址是符合的地址
        this.setData({
          harvestAddressId,
          linkName,
          phone,
          houseNumber,
          address,
          showAddressPicker: false,
          villageName,
          existAddress: true,
          addAddress: 2
        });
      }
      delete app.globalData.harvestAddressId;
      delete app.globalData.address;
      delete app.globalData.villageName;
      delete app.globalData.linkName;
      delete app.globalData.phone;
      delete app.globalData.houseNumber;
      delete app.globalData.exceed;
      delete app.globalData.delete;
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    stopBubble() {},
    async init({ beeperId, info, addressInfo }) {
      this.setData({
        beeperId,
        info,
        addressInfo,
        addressType: addressInfo ? addressInfo.addressType : ''
      });
      if (!addressInfo) return false;
      return await this.getAddress();
    },
    // 获取地址
    async getAddress() {
      // 判断是否有地址，如果有的话就不显示，如果不存在的话就需要根据addressType的不同去选择地址
      const {
        beeperId,
        info: { variantId },
        addressType,
        addressInfo
      } = this.data;
      let params = { beeperId, variantIds: variantId };
      let res = addressInfo;
      console.log(addressInfo);
      // 如果addressType为3的话需要定位获取最近的收获地址
      if (addressType == 3) {
        res = await judgeAuth('scope.userLocation');
        if (!res) {
          await Dialog.confirm({
            title: '提示',
            message: '是否通过定位来获取附近收货地址？'
          });
          if (res === false) {
            res = await openAuth('scope.userLocation');
          }
        }
        if (res !== false) {
          // 是undefined或者为true的时候才定位
          const {
            location: { lat, lng }
          } = await initLocationPersmiss();
          Object.assign(params, { latitude: lat, longitude: lng });
        }

        res = await $api.getAddress(params);
        res = res.data.data;
      }
      const {
        status,
        harvestAddressId,
        linkName,
        phone,
        houseNumber,
        provinceName,
        provinceId,
        cityName,
        cityId,
        areaName,
        areaId,
        streetName,
        streetId,
        villageName,
        villageId,
        off,
        latitude,
        longitude,
        address
      } = res;
      this.setData({
        status,
        existAddress: status ? false : true,
        addAddress: status && addressType == 5 ? 1 : 0,
        harvestAddressId,
        beeperLatitude: latitude,
        beeperLongitude: longitude,
        address,
        linkName,
        phone,
        houseNumber,
        provinceName,
        provinceId,
        cityName,
        cityId,
        areaName,
        areaId,
        streetName,
        streetId,
        villageName,
        villageId,
        off, //off==2表示addressType为2与4，且是第一次填写地址
        inputPerson: off == 2 ? wx.getStorageSync('nickName') : '',
        inputPhone: off == 2 ? wx.getStorageSync('phone') : ''
      });
      return (
        (addressType == 2 && off == 2) ||
        addressType == 3 ||
        (addressType == 4 && off == 2) ||
        (addressType == 5 && this.data.addAddress)
      );
    },
    // 姓名、电话、门牌号输入
    inputChange(e) {
      const {
        currentTarget: {
          dataset: { prop }
        },
        detail: { value }
      } = e;
      this.setData({
        [prop]: value
      });
    },
    // 显示地址列表还是去新增地址
    async judgeAddressGet(e) {
      const { addressType } = this.data;
      console.log(addressType, 184);
      if (addressType == 5) {
        this.toSelectAddress();
      } else {
        this.showAddressPopup();
      }
    },
    // 去编辑或添加地址
    toSelectAddress(e) {
      let item = e && e.currentTarget.dataset.item;
      let {
        addAddress,
        addressType,
        info: { variantId },
        beeperId
      } = this.data;
      if (!item) {
        // item不存在就表示添加收获地址，否则就是编辑收获地址
        let str = addAddress ? '&relationBeeperId=' + beeperId + '&relationBeeperType=' + addressType : '';
        wx.navigateTo({
          url: '/subcontract/person/pages/selectAddress/index?variantIds=' + variantId + str
        });
        return;
      }
      if (item.beeperId) {
        // 如果呼叫器存在就去呼叫器地址选择页面
        wx.navigateTo({
          url:
            '/subcontract/person/pages/beeperAddress/index?id=' + item.beeperId + '&variantIds=' + this.data.variantIds
        });
      } else if (item.harvestAddressId) {
        // beeperId不存在但是harvestAddressId存在就去收货地址选择页面
        wx.navigateTo({
          url:
            '/subcontract/person/pages/selectAddress/index?id=' +
            item.harvestAddressId +
            '&variantIds=' +
            this.data.variantIds
        });
      }
    },
    // 显示收货地址弹框
    async showAddressPopup() {
      const {
        beeperId,
        info: { variantId }
      } = this.data;
      let params = {
        beeperId,
        variantIds: variantId
      };
      let res = await $api.addressList(params);
      res = res.data.data;
      let exceed = false; //这个用来标识第一个超出配送地址的一项
      res.forEach(item => {
        if (!exceed && !item.state) {
          item.exceed = true;
          exceed = true;
        }
      });
      this.setData({
        addressList: res,
        showAddressPicker: true
      });
    },
    // 选中地址列表的地址
    selectAddress(e) {
      let item = e.currentTarget.dataset.item;
      if (!item.state) {
        Toast.fail('该地址不在商家配送范围');
        return;
      }
      this.setData({
        harvestAddressId: item.harvestAddressId,
        linkName: item.linkName,
        phone: item.phone,
        houseNumber: item.houseNumber,
        villageName: item.villageName,
        showAddressPicker: false
      });
    },
    // 关闭收货地址弹框
    closeAddressPopup() {
      this.setData({
        showAddressPicker: false
      });
    },
    // 校验地址
    async validate() {
      let { addressType, existAddress, inputHouseNumber, inputPhone, inputPerson, off, harvestAddressId } = this.data;
      if (!existAddress) return Toast.fail('请完善地址');
      if (off == 2) {
        const reg = /^1(3|4|5|6|7|8|9)\d{9}$/;
        if (!inputPhone) {
          Toast.fail('请输入电话');
          return;
        }
        if (!reg.test(inputPhone)) {
          Toast.fail('电话号码格式错误');
          return;
        }
        if (!inputPerson) {
          Toast.fail('请输入收货人');
          return;
        }
        if (!inputHouseNumber && addressType == 4) {
          Toast.fail('请输入门牌号');
          return;
        }
        harvestAddressId = await this.saveAddress();
      }
      return harvestAddressId;
    },
    // 保存地址
    async saveAddress() {
      let {
        addressType,
        houseNumber,
        linkPhone,
        inputHouseNumber,
        inputPhone,
        inputPerson,
        beeperLatitude,
        beeperLongitude,
        provinceName,
        provinceId,
        cityName,
        cityId,
        areaName,
        areaId,
        streetName,
        streetId,
        villageId,
        villageName,
        beeperId,
        address
      } = this.data;
      let linkName = this.data.linkName;
      if (addressType == 2 || addressType == 4) {
        linkPhone = inputPhone;
        linkName = inputPerson;
        if (addressType == 4) houseNumber = inputHouseNumber;
      }

      const params = {
        latitude: beeperLatitude,
        longitude: beeperLongitude,
        phone: linkPhone,
        linkName,
        address,
        provinceName,
        provinceId,
        cityName,
        cityId,
        areaName,
        areaId,
        streetName,
        streetId,
        villageId,
        houseNumber,
        villageName,
        relationBeeperId: beeperId,
        relationBeeperType: addressType
      };
      const res = await $api.saveAddress(params);
      this.setData({
        off: -1,
        linkName,
        phone: linkPhone,
        houseNumber
      });
      return res.data.data;
    }
  }
});
